package com.cxh.rmsq.ui.activity.self

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.aleyn.mvvm.utils.ActivityCollector
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.common.IntentExtra
import com.cxh.rmsq.databinding.ActivityClueListBinding
import com.cxh.rmsq.databinding.ActivityDakaLocationBinding
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.net.newNet.TreasureViewModel
import com.cxh.rmsq.ui.BaseActivity
import com.cxh.rmsq.ui.adapter.self.CampClockImageNewAdapter
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.utils.dialog.CluePopup
import com.cxh.rmsq.utils.dialog.ShoukuanAccountPopup
import com.cxh.rmsq.utils.loadImage
import com.cxh.rmsq.utils.recyclerview.FullyGridLayoutManager
import com.cxh.rmsq.utils.recyclerview.GridSpacingItemDecoration
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnRequestPermissionListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.permissions.PermissionChecker
import com.luck.picture.lib.permissions.PermissionConfig
import com.luck.picture.lib.permissions.PermissionResultCallback
import com.lxj.xpopup.XPopup
import java.util.Arrays

/**
 * 寻宝藏
 */
class DakaLocationActivity : BaseActivity() {

    private lateinit var binding: ActivityDakaLocationBinding

    private var locationId = ""
    private var activityId = ""
    private var name = ""
    private var activityName = ""
    private var progressId = ""
    private var lat = ""
    private var lng = ""
    var alipay = ""
    var wechat = ""

    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(TreasureViewModel::class.java)
    }
    private val proViewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }

    private var files = ""

    //声明mLocationClient对象
    var mLocationClient: AMapLocationClient? = null

    //声明mLocationOption对象
    var mLocationOption: AMapLocationClientOption? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDakaLocationBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.clToolbar.setPadding(0, 0, 0, 0)
//        findViewById<ConstraintLayout>(R.id.cl_toolbar).setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.transparent))
        BarUtils.setStatusBarLightMode(this, true)

        initLocation()
        name = intent.getStringExtra("name").toString()
        locationId = intent.getStringExtra("locationId").toString()
        progressId = intent.getStringExtra("progressId").toString()
        activityId = intent.getStringExtra("activityId").toString()
        activityName = intent.getStringExtra("activityName").toString()
        Log.e("progressId", progressId + ",activityId=" + activityId)
        binding.tvContent.text =
            "恭喜您成功达到 " + activityName + "-" +
                    name + " 打卡点快快打卡点亮碎片吧！"
        binding.ivBack.setOnClickListener {
            finish()
        }
        binding.ivAdd.setOnClickListener {
            transferCamera()
        }
        binding.ivDel.setOnClickListener {
            binding.ivDel.isVisible = false
            binding.ivCampClockImage.isVisible = false
            binding.ivAdd.isVisible = true
            files = ""
        }
        binding.tvClick.setOnClickListener {
            showLoadingDialog("定位中")
            getLocationData()
            binding.tvLocation.isVisible = true
            binding.tvClick.isVisible = false
        }

        binding.llDaka.setOnClickListener {

            if (isFastClick) {
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(files)) {
                ToastUtils.showToast("请上传现场图片")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(binding.tvLocation.text.toString().trim())) {
                ToastUtils.showToast("未获取位置，请点击获取")
                return@setOnClickListener
            }
            showLoadingDialog("定位中")
            getLocationData()
            var distance = intent.getIntExtra("distance", 0)//允许打卡的最大范围
            var latitude = intent.getDoubleExtra("latitude", 0.0)
            var longitude = intent.getDoubleExtra("longitude", 0.0)
            // 定义两个经纬度点
            val point1 = LatLng(latitude, longitude) // 点1（天安门）
            val point2 = LatLng(lat.toDouble(), lng.toDouble()) // 点2（王府井）

            // 计算两点距离（单位：米）
            val dis = AMapUtils.calculateLineDistance(point1, point2)
            if (dis > distance) {
                XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .asCustom(
                        CluePopup(this,
                            6,
                            name,
                            object : CluePopup.onClick {
                                override fun click(s: String, s1: String) {

                                }
                            })
                    )
                    .show()
            } else {
                val paramsMap = HashMap<String, Any>()
                paramsMap["locationId"] = locationId
                paramsMap["progressId"] = progressId
                paramsMap["clueId"] = activityId
                paramsMap["checkInLocation"] = binding.tvLocation.text.toString().trim()
                paramsMap["photoUrl"] = files
                paramsMap["latitude"] = lat
                paramsMap["longitude"] = lng
                Log.e("paramsMap", paramsMap.toString())
                viewModel.createDakaRecords(paramsMap) {
                    if (it.code == 200) {
                        XPopup.Builder(this)//打卡成功弹窗
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .asCustom(
                                CluePopup(this,
                                    5,
                                    name,
                                    object : CluePopup.onClick {
                                        override fun click(s: String, s1: String) {
                                            viewModel.getPayNum(progressId) { its ->//判断是否已经全部打卡完成
                                                if (its.code == 200) {// 1已完成 0未完成
                                                    if (its.data.completionStatus == 1) {//付款账户弹窗
                                                        if (!TextUtils.isEmpty(its.data.wxPayNum) && !TextUtils.isEmpty(
                                                                its.data.zfbPayNum
                                                            )
                                                        ) {
                                                            XPopup.Builder(this@DakaLocationActivity)
                                                                .dismissOnTouchOutside(false)
                                                                .dismissOnBackPressed(false)
                                                                .asCustom(
                                                                    ShoukuanAccountPopup(this@DakaLocationActivity,
                                                                        1,
                                                                        its.data.zfbPayNum.toString(),
                                                                        its.data.wxPayNum.toString(),
                                                                        activityName,
                                                                        object :
                                                                            ShoukuanAccountPopup.onClick {
                                                                            override fun click(
                                                                                s: Int,
                                                                                s1: String
                                                                            ) {
                                                                                var payType = s //1微信2支付宝
                                                                                //更新打款
                                                                                val paramsMap = HashMap<String, Any>()
                                                                                paramsMap["clueId"] = activityId
                                                                                paramsMap["id"] = progressId
                                                                                paramsMap["payWay"] = payType
                                                                                viewModel.updateProgress(paramsMap) { data ->
                                                                                    if (data.code == 200) {
                                                                                        finish()
                                                                                        ActivityCollector.finishActivity(
                                                                                            ClueListActivity::class.java
                                                                                        )
                                                                                    }
                                                                                }
                                                                            }
                                                                        })
                                                                )
                                                                .show()
                                                        } else {//去填写付款账户弹窗
                                                            XPopup.Builder(this@DakaLocationActivity)
                                                                .dismissOnTouchOutside(false)
                                                                .dismissOnBackPressed(false)
                                                                .asCustom(
                                                                    CluePopup(this@DakaLocationActivity,
                                                                        8,
                                                                        activityName,
                                                                        object : CluePopup.onClick {
                                                                            override fun click(
                                                                                s: String,
                                                                                s1: String
                                                                            ) {
                                                                                startActivityForResult(
                                                                                    Intent(
                                                                                        this@DakaLocationActivity,
                                                                                        EditUserInfoActivity::class.java
                                                                                    ).putExtra("fromDaka",true),
                                                                                    100
                                                                                )
                                                                            }
                                                                        })
                                                                )
                                                                .show()
                                                        }
                                                    } else {//还未全部打卡
                                                        finish()
                                                        ActivityCollector.finishActivity(
                                                            ClueListActivity::class.java
                                                        )
                                                    }
                                                }
                                            }

                                        }
                                    })
                            )
                            .show()
                    } else {
                        ToastUtils.showToast(it.msg)
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                100 -> {
                    alipay = data!!.getStringExtra("alipay").toString()
                    wechat = data!!.getStringExtra("wechat").toString()
                    XPopup.Builder(this@DakaLocationActivity)
                        .dismissOnTouchOutside(false)
                        .dismissOnBackPressed(false)
                        .asCustom(
                            ShoukuanAccountPopup(this@DakaLocationActivity,
                                1,
                                alipay,
                                wechat,
                                activityName,
                                object :
                                    ShoukuanAccountPopup.onClick {
                                    override fun click(
                                        s: Int,
                                        s1: String
                                    ) {
                                        var payType = s////1微信2支付宝
                                        //更新打款
                                        val paramsMap = HashMap<String, Any>()
                                        paramsMap["clueId"] = activityId
                                        paramsMap["id"] = progressId
                                        paramsMap["payWay"] = payType
                                        viewModel.updateProgress(paramsMap) {
                                            if (it.code == 200) {
                                                finish()
                                                ActivityCollector.finishActivity(
                                                    ClueListActivity::class.java
                                                )
                                            }
                                        }
                                    }
                                })
                        )
                        .show()
                }
            }
        }
    }

    private fun transferCamera() {
        //拍照
        val pictureSelector = PictureSelector.create(this)
        pictureSelector!!.openCamera(SelectMimeType.ofImage())
            .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                override fun requestPermission(
                    fragment: Fragment,
                    permissionArray: Array<String>,
                    call: OnRequestPermissionListener
                ) {
                    val permissionInfoDialog = Dialog(fragment.requireActivity())
                    //应用上架要求添加权限使用说明
                    var permissionInfoTitle = ""
                    var permissionInfoContent = ""
                    if (Arrays.equals(
                            permissionArray,
                            PermissionConfig.getReadPermissionArray(
                                fragment.context,
                                SelectMimeType.ofImage()
                            )
                        )
                    ) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_storage)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_storage)
                    } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_camera)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_camera)
                    }
                    if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                            permissionInfoContent
                        )
                    ) {
                        CustomPermissionUtil.showPermissionInfo(
                            fragment.activity,
                            permissionInfoDialog,
                            permissionInfoTitle,
                            permissionInfoContent
                        )
                    }

                    //此处使用图片选择框架的权限申请
                    PermissionChecker.getInstance().requestPermissions(
                        fragment,
                        permissionArray,
                        object : PermissionResultCallback {
                            override fun onGranted() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, true)
                            }

                            override fun onDenied() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, false)
                            }
                        })
                }

                override fun hasPermissions(
                    fragment: Fragment,
                    permissionArray: Array<String>
                ): Boolean {
                    return PermissionChecker.isCheckSelfPermission(
                        fragment.context,
                        permissionArray
                    )
                }
            })
            .setPermissionDeniedListener { fragment, permissionArray, requestCode, call -> //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
                var permissionSetContent = ""
                if (Arrays.equals(
                        permissionArray,
                        PermissionConfig.getReadPermissionArray(
                            fragment.context,
                            SelectMimeType.ofImage()
                        )
                    )
                ) {
                    permissionSetContent = resources.getString(R.string.permission_set_storage)
                } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                    permissionSetContent = resources.getString(R.string.permission_set_camera)
                }
                if (!TextUtils.isEmpty(permissionSetContent)) {
                    CustomPermissionUtil.showPermissionSet(
                        fragment.activity,
                        permissionSetContent,
                        ArrayList(Arrays.asList(*permissionArray))
                    ) { call.onCall(true) }
                }
            }
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                    if (result != null) {
                        val images: MutableList<String> = ArrayList()
                        showLoadingDialog("上传中")
                        proViewModel.updateSinglePic(result[0].realPath) {
                            runOnUiThread {
                                files = it.data
                                binding.ivAdd.isVisible = false
                                binding.ivDel.isVisible = true
                                binding.ivCampClockImage.isVisible = true
                                loadImage(files, binding.ivCampClockImage)
                                Log.e("imgpath", files)
                                dismissLoadingDialog()
                            }
                        }
                    }
                }

                override fun onCancel() {
                }
            })
    }

    private fun initLocation() {
        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption!!.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption!!.isOnceLocation = true
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption!!.isOnceLocationLatest = true
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption!!.isNeedAddress = true
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption!!.isMockEnable = true
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption!!.interval = 1000
        //设置定位请求超时时间，单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption!!.httpTimeOut = 20000
        //关闭缓存机制
        mLocationOption!!.isLocationCacheEnable = false
        try {
            mLocationClient = AMapLocationClient(this)
            //给定位客户端对象设置定位参数
            mLocationClient!!.setLocationOption(mLocationOption)
            mLocationClient!!.setLocationListener { aMapLocation ->
                //获取定位结果
                if (aMapLocation != null) {
                    if (aMapLocation.errorCode == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        if (!TextUtils.isEmpty(aMapLocation.city)) {
                            var address =
                                /*aMapLocation.getCity() + "" + aMapLocation.getDistrict() + "" +*/
                                aMapLocation.address
                            lng = aMapLocation.longitude.toString()
                            lat = aMapLocation.latitude.toString()
                            binding.tvLocation.setText(address)
                            Log.e("address", address)
                        } else {
                            binding.tvLocation.text = ""
                            binding.tvLocation.isVisible = false
                            binding.tvClick.isVisible = true
                            ToastUtils.showToast("未获取到城市名称，请重试")
                        }
                        dismissLoadingDialog()
                    } else {
                        binding.tvLocation.isVisible = false
                        binding.tvClick.isVisible = true
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        if (aMapLocation.errorCode == 12) {
                            ToastUtils.showToast("定位失败:" + "请在设置中打开定位服务开关后重试")
                        } else {
                            ToastUtils.showToast("定位失败:" + aMapLocation.errorInfo)
                        }
                        dismissLoadingDialog()
                    }
                }
            }
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    //获取定位权限
    private fun getLocationData() {
        //应用上架要求添加权限使用说明
        val permissionInfoDialog = Dialog(this)
        CustomPermissionUtil.showPermissionInfo(
            this, permissionInfoDialog,
            resources.getString(R.string.permission_info_title_location_camp_clock),
            resources.getString(R.string.permission_info_content_location_camp_clock)
        )

        //获取定位权限并进行定位
        XXPermissions.with(this)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    if (allGranted) {
                        permissionInfoDialog.dismiss()

                        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                        mLocationClient!!.stopLocation()
                        mLocationClient!!.startLocation()
                    }
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                    permissionInfoDialog.dismiss()
                    dismissLoadingDialog()
                    binding.tvLocation.isVisible = false
                    binding.tvClick.isVisible = true
                    ToastUtils.showToast("定位权限被禁止，请前往手机设置>应用管理>人脉社区>权限，开启定位权限，以正常使用此功能。")
                    //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
//                    CustomPermissionUtil.showPermissionSet(
//                        this@DakaLocationActivity,
//                        resources.getString(R.string.permission_set_location_camp_clock),
//                        permissions
//                    ) { //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
//                        mLocationClient!!.stopLocation()
//                        mLocationClient!!.startLocation()
//                    }
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient!!.stopLocation() //停止定位后，本地定位服务并不会被销毁
        mLocationClient!!.onDestroy() //销毁定位客户端，同时销毁本地定位服务。
    }
}